<!-- MyFollowsPage.vue -->
<template>
  <UserRelationList title="我的关注" backPath="/user" :userList="followsList" :pageNum="pageNum"
    @handleItem="handleFollow" />
</template>

<script setup>
import UserRelationList from '@/components/common/UserRelationList.vue'
import { getFollowersAPI } from "@/api/user/user";
import { useUserStore } from "@/store/modules/user/user";
import { triggerFollowAPI } from "@/api/message/message";
import { getCurrentInstance, ref, onMounted } from 'vue'

const { proxy } = getCurrentInstance()
const userStore = useUserStore()
const userId = userStore.userInfo.userId
const followsList = ref([])
const pageNum = ref(1)

// 获取关注列表数据
async function getFollowsList() {
  const res = await getFollowersAPI(userId, pageNum.value)
  if (res.code === 200) {
    followsList.value = res.data
  }
}

// 处理关注/取消关注（父组件负责API调用）
async function handleFollow({ item, newStatus }) {
  try {
    // 调用关注接口（关注列表的API）
    const res = await triggerFollowAPI(userId, item.userId)
    if (res.code === 200) {
      // 更新本地数据（使用组件计算的newStatus）
      const index = followsList.value.findIndex(i => i.userId === item.userId)
      if (index > -1) {
        followsList.value[index].bothStatus = newStatus
      }
      // 提示用户
      proxy.$toast({ message: '操作成功'})
    }
  } catch (error) {
    console.log(error)
    proxy.$toast({ message: '操作失败', type: 'error' })
  }
}

onMounted(() => {
  getFollowsList()
})
</script>